<?php


namespace App\Http\Controllers\Admin\Critical;


use App\Enums\CriticalEnum;
use App\Enums\RedisKeyEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use App\Services\Tools\HelperService;
use App\Traits\AdminLog;
use Illuminate\Http\Request;
use Symfony\Component\Console\Helper\Helper;
use function Complex\argument;

//暴击奖池查看中奖次数
class CriticalPoolPrizeController extends BaseController
{
    use AdminLog;
    private $moduleId = CriticalEnum::MODULE_TREE;

    /**
     * @api {get} /critical/pool/prize 暴击奖池详情(个人奖池)
     * @apiGroup  暴击奖池
     *
     * @apiParam {int} user_id 用户id
     * @apiParam {int} pool_type 奖池类型(40特殊个人 50个人独立)
     *
     * @apiSuccessExample 成功响应
     *{
    "code": 200,
    "data": {
    "list": [
    {
    "id": 1,
    "module": 1,
    "gift_id 礼物id": 542,
    "winner_num": 0,
    "winner_times": 0,
    "status": 1,
    "created_at": "2021-10-20 10:47:50",
    "updated_at": "2021-10-20 10:47:50",
    "winner_num_pool 当前奖池中奖个数(取这个字段)": 0,
    "winner_times_pool 当前奖池中奖次数": 0,
    "name 名称": "巫师帽",
    "price 价格": 1000,
    "picture 图片": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/452a248f70c245ca1da666dd5607f139WpjAs.png"
    },
    {
    "id": 7,
    "module": 1,
    "gift_id": 546,
    "winner_num": 0,
    "winner_times": 0,
    "status": 1,
    "created_at": "2021-10-21 21:23:52",
    "updated_at": "2021-10-21 21:23:52",
    "winner_num_pool": 0,
    "winner_times_pool": 0,
    "name": "精灵的祝福",
    "price": 131400,
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/611b30765b200.png"
    }
    ],
    "level_coin_num 剩余奖池价值(取他)": 0,
    "redis_level_coin_num 缓存剩余奖池价值(忽略)": "7200"
    },
    "message": ""
    }
     */
    public function all(Request $request)
    {
        $param = $request->only('user_id','pool_type');
        $v = app('validator')->make($param, [
            'user_id' => 'required|integer',
            'pool_type' => "required|integer",
        ]);
        if ($v->fails()){
            throw new BasicException(0, $v->errors()->first());
        }

        $userId = $param['user_id'];
        $poolType = $param['pool_type'];
        if(!in_array($poolType,[
            CriticalEnum::TREE_SELF_POOL_SPECIAL,
            CriticalEnum::TREE_SELF_POOL_INDEPENDENT
        ])){
            throw new BasicException(0, '奖池类型错误');
        }

        $list = app('model_critical_prize')->where([
            'module' => $this->moduleId,
            'status' =>1
        ])->get();
        $list = empty($list)?[]:$list->toArray();
        $levelCoinNum = app('model_critical_pool_coin_level')->where('module',$this->moduleId)->where('pool_type',$poolType)->where('user_id',$userId)->first(['level_coin_num']);
        $levelCoinNum = empty($levelCoinNum)?0:$levelCoinNum['level_coin_num'];
        $coinMoneyKey = "critical:level:coin:num:".$this->moduleId.":".$poolType.":".$userId;//剩余的金币数
        $redisLevelCoinNum = app('redis')->get($coinMoneyKey);

        $poolPrizeList = app('model_critical_pool_prize')->where('module',$this->moduleId)->where('pool_type',$poolType)->where('user_id',$userId)->get();
        $poolPrizeList = empty($poolPrizeList)?[]:$poolPrizeList->toArray();
        $poolPrizeList = HelperService::indexToAssoc($poolPrizeList,'gift_id');
        $giftIds = HelperService::getArrayColumn($list,'gift_id');
        if(!empty($giftIds)){
            $gifts = app('model_gift')->whereIn('id',$giftIds)->get(['id','name','price','picture']);
            $gifts = empty($gifts)?[]:$gifts->toArray();
            $gifts = HelperService::indexToAssoc($gifts,'id');
        }else{
            $gifts = [];
        }

        foreach ($list as $k=>$v){
            $list[$k]['winner_num_pool'] = isset($poolPrizeList[$v['gift_id']])?$poolPrizeList[$v['gift_id']]['winner_num']:0;
            $list[$k]['winner_times_pool'] = isset($poolPrizeList[$v['gift_id']])?$poolPrizeList[$v['gift_id']]['winner_times']:0;
            $list[$k]['name'] = isset($gifts[$v['gift_id']])?$gifts[$v['gift_id']]['name']:'';
            $list[$k]['price'] = isset($gifts[$v['gift_id']])?$gifts[$v['gift_id']]['price']:'';
            $list[$k]['price'] = isset($gifts[$v['gift_id']])?$gifts[$v['gift_id']]['price']:0;
            $list[$k]['picture'] = isset($gifts[$v['gift_id']])?$gifts[$v['gift_id']]['picture']:'';
        }
        return Response::sendData([
            'list' => $list,
            'level_coin_num' => $levelCoinNum,
            'redis_level_coin_num' => (int)($redisLevelCoinNum??0),
        ]);
    }
    /**
     * @api {post} /critical/num/set 设置暴击数量
     * @apiGroup  暴击奖池
     *
     * @apiParam {int} critical_times 暴击数量
     * @apiParam {int} pool_type 奖池类型(1公用奖池 40特殊个人 50个人独立)
     * @apiParam {int} pool_type_id 奖池id
     * @apiParam {int} gift_id 礼物id
     * @apiParam {int} user_id 用户id
     * @apiParam {int} is_next 是否本期奖池 1否 0是
     *
     * @apiSuccessExample {json} Response-Example

     * {
    "code": 200,
    "data": [],
    "message": "设置成功"
    }
     */
    public function setCriticalNum(Request  $request){
        $param = $request->only('critical_times','pool_type','gift_id','user_id','is_next','pool_type_id');
        $v = app('validator')->make($param, [
            'critical_times' => 'required|integer',
            'pool_type' => "required|integer",
            'gift_id' => "required|integer",
            'user_id' => "required|integer",
            'is_next' => "required|in:0,1",
            'pool_type_id' => "required",
        ]);
        if ($v->fails()){
            throw new BasicException(0, $v->errors()->first());
        }
        $criticalTimes = $param['critical_times'];
        $isNext = $param['is_next'];
        $poolType = $param['pool_type'];
        $giftId = $param['gift_id'];
        $userId = $param['user_id'];
        $poolTypeId = $param['pool_type_id'];
        if($poolType == CriticalEnum::TREE_COMMON_POOL){  //公池
            $model = $isNext?app('model_lucky_tree_next'):app('model_lucky_tree');
            $userId = 0 ;
        }else if($poolType == CriticalEnum::TREE_SELF_POOL_SPECIAL){  //特殊个人
            $model = $isNext?app('model_personal_pool'):app('model_personal_pool_user_detail');
        }else if($poolType == CriticalEnum::TREE_SELF_POOL_INDEPENDENT){  //独立个人
            $model = $isNext?app('model_independent_pool'):app('model_independent_pool_user_detail');
        }else{
            throw new BasicException(0, '类型错误');
        }
        $criticalGifts = app('model_critical_prize')->getModuleGiftIds(CriticalEnum::MODULE_TREE);
        if(!in_array($giftId,$criticalGifts)){
            throw new BasicException(0, '该礼物不允许设置暴击数量');
        }
        $where = [
            'type' => $poolTypeId,
            'gift_id' => $giftId,
        ];
        $moduleId = $this->moduleId;
        if($poolType != CriticalEnum::TREE_COMMON_POOL && !$isNext){
            $where['user_id'] = $userId;
        }
        $detail = $model->where($where)->first();
        if(empty($detail)){
            throw new BasicException(0, '目标礼物不在奖池内');
        }
        $detail = $detail->toArray();
        if($criticalTimes>$detail['number']){
            throw new BasicException(0, '暴击次数不能大于剩余数量');
        }
        if($criticalTimes==$detail['critical_times']){
            return Response::sendData([],'设置成功');
        }
        //后台设置编辑锁，防止前端抽奖中更改库存
        $lockKey = "critical:lock:set:num:".$isNext.":".$moduleId.":".$poolType.":".$userId;
        $uk =  HelperService::uniqidReal();
        $redis = app('redis');
        $isLock = $redis->set($lockKey,$uk,'ex',3,'nx');
        if(!$isLock){
            throw new BasicException(0, '设置失败,奖池抽取中禁止设置暴击数量');
        }
        $res = $model->where([
            'id' => $detail['id']
        ])->update([
            'critical_times' => $criticalTimes
        ]);
        if(!$res){
            throw new BasicException(0, '设置失败');
        }
        if($redis->get($lockKey) == $uk){
            $redis->del($lockKey);
        }
        return Response::sendData([],'设置成功');
    }
}